package com.qf.admin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.qf.admin.entity.Goods;
import com.qf.admin.service.IGoodsService;
import com.qf.admin.vo.ExcelGoods;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelGoodsListener extends AnalysisEventListener<ExcelGoods> {

    private IGoodsService goodsService;

    public ExcelGoodsListener(IGoodsService goodsService) {
        this.goodsService = goodsService;
    }

    //每2000条数据读取一次
    private Integer batch_size = 2000;

    //创建集合封装读取到的每一条数据
    private List<Goods> goodsList = new ArrayList<>(batch_size);


    @Override
    public void invoke(ExcelGoods excelGoods, AnalysisContext analysisContext) {

        Date date = new Date();
        //将excelGoods中的数据封装到goods中
        Goods goods = new Goods();

        goods.setTid(excelGoods.getTid());
        goods.setType(excelGoods.getType());
        goods.setGid(excelGoods.getGid());
        goods.setPrice(excelGoods.getPrice());
        goods.setTitle(excelGoods.getTitle());
        goods.setCreateTime(excelGoods.getCreateTime());
        goods.setUpdateTime(date);
        goods.setStatus(excelGoods.getStatus());
        goods.setStock(excelGoods.getStock());

        goodsList.add(goods);

        if (goodsList.size() >= batch_size){
            //将数据添加到数据库中
            goodsService.batchInsert(goodsList);

            //清空集合并释放内存
            goodsList.clear();
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        //当数据大于0小鱼2000时
        if (goodsList.size()>0){
            goodsService.batchInsert(goodsList);
            goodsList.clear();
        }

    }
}
